#include "VoiceRecognition.h"
#include <QStandardPaths>
#include <QMediaDevices>
#include <QCoreApplication>
#include <QDir>
// 主要负责音频录制到文件

VoiceRecognition::VoiceRecognition(const QString& outputDir, QObject *parent) 
    : QObject(parent), m_isRecording(false) 
{
    // 确定输出目录
    QString savePath;
    if (!outputDir.isEmpty() && QDir(outputDir).exists()) {
        savePath = outputDir;
    } else {
        savePath = QCoreApplication::applicationDirPath();  // 默认：exe所在目录，即build文件夹下
    }

    // 创建录音文件路径
    m_tempFilePath = QDir(savePath).absoluteFilePath("voice_record.pcm");
    qDebug() << "录音文件将保存到:" << m_tempFilePath;
}

void VoiceRecognition::startRecording() {
    if (m_isRecording) {
        qWarning() << "录音正在进行中，忽略重复启动";
        return;
    }

    //检查录音文件路径
    QFileInfo fileInfo(m_tempFilePath);
    QDir dir = fileInfo.dir();
    if (!dir.exists()) {
        if (!dir.mkpath(".")) {
            qWarning() << "无法创建目录:" << dir.path();
            return;
        }
    }

    // 设置音频格式（16kHz, 16-bit, 单声道）
    QAudioFormat format;
    format.setSampleRate(16000);
    format.setChannelCount(1);
    format.setSampleFormat(QAudioFormat::Int16);

    // 检查设备支持
    QAudioDevice inputDevice = QMediaDevices::defaultAudioInput();
    if (inputDevice.isNull()) {
        qWarning() << "无可用音频输入设备";
        return;
    }
    if (!inputDevice.isFormatSupported(format)) {
        qWarning() << "Default format not supported, trying nearest...";
        //format = inputDevice.nearestFormat(format);
    }

    // 初始化录音文件
    m_audioFile = new QFile(m_tempFilePath, this);
    if (!m_audioFile->open(QIODevice::WriteOnly | QIODevice::Truncate)) {
        qWarning() << "Could not open audio file for writing";
        return;
    }

    // 启动录音
    m_audioSource = new QAudioSource(inputDevice, format, this);
    m_audioDevice = m_audioSource->start();
    connect(m_audioDevice, &QIODevice::readyRead, [this]() {
        m_audioFile->write(m_audioDevice->readAll());
    });

    qDebug() << "Recording started successfully.";
    m_isRecording = true;
    emit recordingStarted();
}

void VoiceRecognition::stopRecording() {
    if (!m_isRecording) return;

    m_audioSource->stop();// 关闭录音源
    m_audioFile->close(); //关闭录音文件
    m_isRecording = false;
    qDebug() << "录音已停止，文件大小:" << QFileInfo(m_tempFilePath).size() << "字节";
    emit recordingStopped();
}

QString VoiceRecognition::getRecordedFilePath() const {
    return m_tempFilePath;
}